<template>
  <div class="container">
    <h1 align="center">汽车销量报表</h1>
    <!--创建Dom结构（并且设定div的大小）用来展示echars图表-->
    <div id="main" style="width: 100%; height: 500px; margin: 0 auto"></div>
  </div>
</template>

<script>
import * as echarts from "echarts"; //导入echarts的所有组件

import { getCarList } from "@/api/car/car";

export default {
  data() {
    return { carList: [] };
  },
  mounted() {
    this.fetchCarList();
  },
  methods: {
    async fetchCarList() {
      try {
        const response = await getCarList();
        this.carList = response.rows;
        this.drawChart();
      } catch (error) {
        console.error("Error fetching car list:", error);
      }
    },
    drawChart() {
      var chartDom = document.getElementById("main");
      var myChart = echarts.init(chartDom);
      var option;

      const carData = this.carList;

      // 提取年份并去重排序
      const years = Array.from(
        new Set(carData.map((car) => car.date.split("-")[0]))
      ).sort();
      // 提取汽车品牌并去重
      const carNames = Array.from(new Set(carData.map((car) => car.carName)));
      // 构建目标二维数组;
      const result = [["product", ...years]];
      carNames.forEach((carName) => {
        const row = [carName];
        years.forEach((year) => {
          const sales =
            carData.find(
              (car) =>
                car.carName === carName && car.date.split("-")[0] === year
            )?.salesVolume || 0;
          row.push(sales);
        });
        result.push(row);
      });

      console.log(result);

      option = {
        legend: {},
        tooltip: {
          trigger: "axis",
          showContent: false,
        },
        dataset: {
          source: result,
        },
        xAxis: { type: "category" },
        yAxis: { gridIndex: 0 },
        grid: { top: "55%" },
        series: [
          {
            type: "line",
            smooth: true,
            seriesLayoutBy: "row",
            emphasis: { focus: "series" },
          },
          {
            type: "line",
            smooth: true,
            seriesLayoutBy: "row",
            emphasis: { focus: "series" },
          },
          {
            type: "line",
            smooth: true,
            seriesLayoutBy: "row",
            emphasis: { focus: "series" },
          },
          {
            type: "line",
            smooth: true,
            seriesLayoutBy: "row",
            emphasis: { focus: "series" },
          },
          {
            type: "pie",
            id: "pie",
            radius: "30%",
            center: ["50%", "25%"],
            emphasis: {
              focus: "self",
            },
            label: {
              // 修改formatter函数，添加单位“辆”
              formatter: function (params) {
                return `${params.name}: ${params.value[1]}辆 (${params.percent}%)`;
              },
            },
            encode: {
              itemName: "product",
              value: "2023",
              tooltip: "2023",
            },
          },
        ],
      };

      myChart.on("updateAxisPointer", function (event) {
        const xAxisInfo = event.axesInfo[0];
        if (xAxisInfo) {
          const dimension = xAxisInfo.value + 1;
          myChart.setOption({
            series: {
              id: "pie",
              label: {
                // 修改动态更新的formatter函数，添加单位“辆”
                formatter: function (params) {
                  return `${params.name}: ${params.data[dimension]}辆 (${params.percent}%)`;
                },
              },
              encode: {
                value: dimension,
                tooltip: dimension,
              },
            },
          });
        }
      });

      myChart.setOption(option);
    },
  },
};
</script>
